package com.hmkj.web.controller.wx;

import com.hmkj.core.api.wechat.utils.WechatUtils;
import com.hmkj.core.service.wx.WxAccountService;
import com.hmkj.web.controller.GenericController;
import lombok.extern.log4j.Log4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.function.Function;

/**
 * Created by Donfy on 2017/7/1.
 */
@Log4j
@RestController
@RequestMapping(GenericController.BASE_API_URL+"/wx")
public class WxGeneralController {

    private static final String OK = "success";

    @Resource
    private WxAccountService wxAccountService;

    private Function<Map<String, String>, String> router(Map<String, String> map) {
        String msgType = map.get("MsgType");
        String event = map.get("Event");
        log.info("msgType=" + msgType + ",event=" + event);
        switch (event == null ? "" : event) {
            /** 用户关注事件 */
            case "subscribe":
                return wxAccountService::subscribe;
            case "SCAN":
                return wxAccountService::subscribe;
        }
        return m -> {
            log.info("微信回调事件未定义MsgType=" + m.get("MsgType") + ",Event=" + m.get("Event"));
            return OK;
        };
    }

    @RequestMapping(method = RequestMethod.GET)
    public String get(HttpServletRequest request) {
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        log.info("signature=" + signature + ",timestamp=" + timestamp + ",nonce=" + nonce + ",echostr=" + echostr);
        if (wxAccountService.checkSignature(signature, timestamp, nonce)) {
            return echostr;
        }
        return "";
    }

    @RequestMapping(method = RequestMethod.POST, produces = "application/xml;charset=UTF-8")
    public String post(HttpServletRequest request) throws Exception {
        log.info(request);
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
//        String echostr = request.getParameter("echostr");
        if (wxAccountService.checkSignature(signature, timestamp, nonce)) {
            Map<String, String> map = WechatUtils.parseXml(request);
            log.info(map);
            return router(map).apply(map);
        }
        return "";
    }
}
